package com.trace.pplos.parse.common;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;

/**
 * Created by goldzql on 2017/8/5.
 */
public class CompressUtils {

    public static final int BUFFER_SIZE = 2048;

    private final static Logger logger = LoggerFactory.getLogger(CompressUtils.class);
    /**
     * 解压到指定目录
     * @param zipPath
     * @param descDir
     */
    public static boolean unZipFiles(String zipPath,String descDir){
        return unZipFiles(new File(zipPath), descDir);
    }
    /**
     * 解压文件到指定目录
     * @param zipFile
     * @param descDir
     */
    @SuppressWarnings("rawtypes")
    public static boolean unZipFiles(File zipFile,String descDir){
        InputStream in = null;
        OutputStream out = null;
        try {
            File pathFile = new File(descDir);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            ZipFile zip = new ZipFile(zipFile);
            for (Enumeration entries = zip.getEntries(); entries.hasMoreElements(); ) {
                ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                in = zip.getInputStream(entry);
                String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
                //判断路径是否存在,不存在则创建文件路径
                File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
                if (!file.exists()) {
                    file.mkdirs();
                }
                //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
                if (new File(outPath).isDirectory()) {
                    continue;
                }
                logger.info(outPath);
                out = new FileOutputStream(outPath);
                byte[] buf1 = new byte[BUFFER_SIZE];
                int len;
                while ((len = in.read(buf1)) > 0) {
                    out.write(buf1, 0, len);
                }
            }
            zip.close();
            return true;
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
                return false;
            }
        }
    }

    public static void main(String[] args) throws Exception {
        unZipFiles("d:/syrkdj-20171016002654.zip", "E:/pplos/load/gather/oss/syrkdj/20170806/");
    }
}
